package com.example.messagemodule.widget;

import static androidx.core.content.FileProvider.getUriForFile;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.examination.mlib.constants.AllStringConstants;
import com.examination.mlib.manager.PermissionManager;
import com.example.messagemodule.R;
import com.example.messagemodule.adapter.ConversationMoreAdapter;
import com.example.messagemodule.constants.ConversationMoreConstants;
import com.example.messagemodule.entity.ConversationMore;
import com.example.messagemodule.entity.TalkEntity;
import com.example.messagemodule.ui.ConversationActivity;
import com.hyphenate.chat.EMMessage;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.CommonUtils;
import com.yilijk.base.utils.KeyboardUtils;
import com.yilijk.base.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by SHICHENG
 * <p>
 * Time on
 */
public class ConversationInputView extends LinearLayout {

    public interface InputViewClickListener{

        void sendTXTmsg(String txtString);

        void sendVOICEmsg(String path,int length);

        void refreshPosition();

        void adapterCarame();

        void adapterImage();

    }

    private InputViewClickListener inputViewClickListener;

    public void setInputViewClickListener(InputViewClickListener inputViewClickListener) {
        this.inputViewClickListener = inputViewClickListener;
    }

    public ConversationInputView(Context context) {
        super(context);
        initView();
    }

    public ConversationInputView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public ConversationInputView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    public ConversationInputView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView();
    }

    View view;
    private LinearLayout conversationInput;
    private LinearLayout fastButtonLl;
    private LinearLayout fastButtonSendPic;
    private ImageView conversationChangeVoiceInput;
    private EditText conversationInputEt;
    private TalkingButton conversationVoiceBt;
    private TextView conversationSendMessage;
    private ImageView convetsationShowMore;
    private RecyclerView conversationMore;

    private ConversationMoreAdapter conversationMoreAdapter;
    private ArrayList<ConversationMore> moreItem;

    void initView(){
        moreItem = new ArrayList();
        moreItem.add(new ConversationMore(ConversationMoreConstants.CAMERA_ID, CommonUtils.imageTranslateUri(getContext(), R.drawable.conversation_camera), "拍摄"));
        moreItem.add(new ConversationMore(ConversationMoreConstants.PICTURE_ID, CommonUtils.imageTranslateUri(getContext(), R.drawable.conversation_picture), "上传图片"));

        view = LayoutInflater.from(getContext()).inflate(R.layout.view_conversation_input, this);
        conversationInput = (LinearLayout) findViewById(R.id.conversation_input);
        fastButtonLl = (LinearLayout) findViewById(R.id.fast_button_ll);
        fastButtonSendPic = (LinearLayout) findViewById(R.id.fast_button_send_pic);
        conversationChangeVoiceInput = (ImageView) findViewById(R.id.conversation_change_voice_input);
        conversationInputEt = (EditText) findViewById(R.id.conversation_input_et);
        conversationVoiceBt = (TalkingButton) findViewById(R.id.conversation_voice_bt);
        conversationSendMessage = (TextView) findViewById(R.id.conversation_sendMessage);
        convetsationShowMore = (ImageView) findViewById(R.id.convetsation_show_more);
        conversationMore = (RecyclerView) findViewById(R.id.conversation_more);

        conversationMore.setLayoutManager(new GridLayoutManager(getContext(), 4));
        conversationMoreAdapter = new ConversationMoreAdapter(R.layout.conversation_more_item, moreItem);
        conversationMore.setAdapter(conversationMoreAdapter);
        conversationMoreAdapter.notifyDataSetChanged();

        viewListener();
    }

    void viewListener(){
           //更多菜单点击
        ClickUtils.setAdapterItemFastOnClickListener(conversationMoreAdapter, new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //判断权限是否存在
//                if (!CommonUtils.checkPermission(ConversationActivity.this, "android.permission.CAMERA")) {
//                    CommonUtils.getModuleCommonUtils().setRequestPermission(ConversationActivity.this, new String[]{
//                            "android.permission.CAMERA"
//                    }, 1002);
//                    return;
//                }
//                if (!CommonUtils.checkPermission(ConversationActivity.this, "android.permission.WRITE_EXTERNAL_STORAGE")) {
//                    CommonUtils.getModuleCommonUtils().setRequestPermission(ConversationActivity.this, new String[]{
//                            "android.permission.WRITE_EXTERNAL_STORAGE",
//                            "android.permission.READ_EXTERNAL_STORAGE"
//                    }, 1002);
//                    return;
//                }
                switch (position) {
                    case 0:
                        if (inputViewClickListener != null){
                            inputViewClickListener.adapterCarame();
                        }
                        break;
                    case 1:
                        if (inputViewClickListener != null){
                            inputViewClickListener.adapterImage();
                        }
                        break;
                }
            }
        });
        //长按发送语音
        conversationVoiceBt.setOnTouchListener(new TalkingButton.TalkingTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    //按下开始录制
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                }
                return super.onTouch(v, event);
            }
        }, new TalkingButton.TouchCallback() {
            @Override
            public void onSuccess(String voicePath, int voiceLength) {
                if (inputViewClickListener != null){
                    inputViewClickListener.sendVOICEmsg(voicePath,voiceLength);
                }
//                EMMessage voiceSendMessage = EMMessage.createVoiceSendMessage(voicePath, voiceLength, getCurrentToAccount());
//                sendEMMessage(getChatType(), voiceSendMessage, false);
            }

            @Override
            public void onError() {

            }

            @Override
            public void onToText(String voicePath, int voiceLength) {
                HttpUtils.uploadAmr(AllStringConstants.mp32text, new File(voicePath), new HttpCallBack<TalkEntity>() {
                    @Override
                    public void onSuccess(TalkEntity talkEntity, int i) {
                        TalkingButton.messageVoiceTotextContent.setVisibility(View.VISIBLE);
                        TalkingButton.audiowaveview.setVisibility(View.GONE);
                        TalkingButton.messageVoiceTexterrorBg.setVisibility(View.GONE);
                        TalkingButton.messageVoiceTotextBg.setVisibility(View.VISIBLE);
                        Glide.with(getContext()).load(R.drawable.message_voice_totext_success).transform(new CenterCrop(), new CircleCrop()).into(TalkingButton.messageVoiceTotextText);
                        TalkingButton.messageVoiceTotextText.setEnabled(true);
                        if (talkEntity.isResult()) {
                            if (talkEntity.getData() != null) {
                                try {
                                    TalkingButton.messageVoiceTotextUpdata.setVisibility(View.VISIBLE);
                                    JSONArray jsonObject = new JSONArray(talkEntity.getData());
                                    TalkingButton.setToTextResult(true, jsonObject.get(0).toString());
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            } else {
                                TalkingButton.setToTextResult(false, "未识别到文字");
                            }
                        }
                    }

                    @Override
                    public void onFailure(String s, int code) {
                        if (code == 400 || code == 500) {
                            TalkingButton.messageVoiceTotextText.setEnabled(false);
                            Glide.with(getContext()).load(R.drawable.message_voice_totext_error).transform(new CenterCrop(), new CircleCrop()).into(TalkingButton.messageVoiceTotextText);
                            TalkingButton.messageVoiceTotextContent.setVisibility(View.VISIBLE);
                            TalkingButton.audiowaveview.setVisibility(View.GONE);
                            TalkingButton.messageVoiceTexterrorBg.setVisibility(View.VISIBLE);
                            TalkingButton.messageVoiceTotextBg.setVisibility(View.GONE);
                            TalkingButton.setToTextResult(false, "语音识别失败");
                        }
                    }
                });
            }
        });
        //发送原语音
        ClickUtils.setFastOnClickListener(conversationVoiceBt.messageVoiceTotextSendvoice, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inputViewClickListener != null){
                    inputViewClickListener.sendVOICEmsg(TalkingButton.getVoicePath(), TalkingButton.getVoiceLength());
                }
//                EMMessage voiceSendMessage = EMMessage.createVoiceSendMessage(TalkingButton.getVoicePath(), TalkingButton.getVoiceLength(), getCurrentToAccount());
//                sendEMMessage(getChatType(), voiceSendMessage, false);
                conversationVoiceBt.dismissTalkingButtonPop();
            }
        });
        //语音转文字发送
        ClickUtils.setFastOnClickListener(conversationVoiceBt.messageVoiceTotextText, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(TalkingButton.getToTextResult())) {
                    if (inputViewClickListener != null){
                        inputViewClickListener.sendTXTmsg(TalkingButton.getToTextResult());
                    }
                    conversationVoiceBt.dismissTalkingButtonPop();
                } else {
                    ToastUtils.make().setBgColor(getContext().getResources().getColor(R.color.color_99000000))
                            .setTextColor(getContext().getResources().getColor(R.color.white))
                            .show("不能发送空消息");
                }
            }
        });
        //显示更多切换点击
        ClickUtils.setFastOnClickListener(convetsationShowMore, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inputViewClickListener != null){
                    inputViewClickListener.refreshPosition();
                }
                conversationMore.setVisibility(conversationMore.getVisibility() == VISIBLE ? View.GONE : View.VISIBLE);
            }
        });
        //发送文本消息
        ClickUtils.setFastOnClickListener(conversationSendMessage, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inputViewClickListener != null){
                    if (TextUtils.isEmpty(conversationInputEt.getText().toString())){
                        ToastUtils.make().setBgColor(getContext().getResources().getColor(R.color.color_99000000))
                                .setTextColor(getContext().getResources().getColor(R.color.white))
                                .show("不能发送空消息");
                    }else{
                        inputViewClickListener.sendTXTmsg(conversationInputEt.getText().toString());
                        conversationInputEt.setText("");
                    }
                }
            }
        });

        //语音文本切换点击
        ClickUtils.setFastOnClickListener(conversationChangeVoiceInput, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (conversationVoiceBt.getVisibility() == VISIBLE) {
                    Glide.with(getContext()).load(R.drawable.voice_open).into(conversationChangeVoiceInput);
                    KeyboardUtils.openKeybord();
                    conversationVoiceBt.setVisibility(View.GONE);
                    conversationInputEt.setVisibility(View.VISIBLE);

                } else {
                    Glide.with(getContext()).load(R.drawable.input_open).into(conversationChangeVoiceInput);
                    KeyboardUtils.closeKeybord((Activity) getContext());
                    conversationVoiceBt.setVisibility(View.VISIBLE);
                    conversationInputEt.setVisibility(View.GONE);
                }
                if (inputViewClickListener != null){
                    inputViewClickListener.refreshPosition();
                }
                conversationMore.setVisibility(View.GONE);
            }
        });
        //输入框监听
        conversationInputEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String trim = conversationInputEt.getText().toString().trim();
                conversationSendMessage.setVisibility(trim.length() > 0 ? View.VISIBLE : View.GONE);
                convetsationShowMore.setVisibility(trim.length() > 0 ? View.GONE : View.VISIBLE);
            }
        });
    }

    //设置输入框提示
    public void setInputHint(String s){
        conversationInputEt.setHint(s);
    }

    //禁用输入框
    public void forbiddenInput(boolean forbidden){
        conversationInputEt.setEnabled(forbidden);
        conversationChangeVoiceInput.setEnabled(forbidden);
        convetsationShowMore.setEnabled(forbidden);
        conversationMore.setVisibility(forbidden ? View.VISIBLE : View.GONE);
    }

    //获取当前输入框的内容
    public String getCurrentContent(){
        return conversationInputEt.getText().toString();
    }
    //设置当前输入框的内容
    public void setCurrentContent(String content){
        conversationInputEt.setText(content);
    }

    public View getInputView(){
        return conversationInputEt;
    }

    public View getSendView() {
        return conversationSendMessage;
    }

    //是否能发送消息
    public void setCanSendMsg(boolean show){
        conversationInput.setVisibility(show ? VISIBLE : GONE);
    }

    //是否展示快捷发送按钮
    public void setShortCurButton(boolean show){
        fastButtonLl.setVisibility(show ? VISIBLE : GONE);
    }

}
